package cn._2dland.uploader.utils;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * RSA加密类
 * 
 * @author deadblue
 */
public class RSA {

	/** 加密器 */
	private Cipher cipher;
	/** 加密公钥 */
	private PublicKey key;

	public RSA(String modulus, String exponent) {
		try {
			// 生成公钥
			BigInteger m = new BigInteger(modulus, 16);
			BigInteger e = new BigInteger(exponent, 16);
			RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
			KeyFactory kfc = KeyFactory.getInstance("RSA");
			key = kfc.generatePublic(keySpec);
			
			// 初始化加密器
			cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加密
	 * 
	 * @param data
	 * @return
	 */
	public byte[] encrypt(byte[] data) {
		byte[] result = null;
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key);
			cipher.update(data);
			result = cipher.doFinal();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		return result;
	}

}
